using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyPool : SingletonMono<EnemyPool>
{
    [Header("敌人对象池设置")]
    public GameObject enemyPrefab;
    public int initialPoolSize = 10;
    
    private Queue<GameObject> enemyPool = new Queue<GameObject>();
    private List<GameObject> activeEnemies = new List<GameObject>();

    private void Start()
    {
        InitializePool();
    }

    // 初始化对象池
    private void InitializePool()
    {
        for (int i = 0; i < initialPoolSize; i++)
        {
            GameObject enemy = Instantiate(enemyPrefab, transform);
            enemy.SetActive(false);
            enemyPool.Enqueue(enemy);
        }
    }

    // 从池中获取敌人
    public GameObject GetEnemy(Vector3 position)
    {
        if (enemyPool.Count == 0)
        {
            ExpandPool(5); // 如果池空了就扩展
        }

        GameObject enemy = enemyPool.Dequeue();
        enemy.transform.position = position;
        enemy.SetActive(true);
        activeEnemies.Add(enemy);
        return enemy;
    }

    // 回收敌人
    public void ReturnEnemy(GameObject enemy)
    {
        if (null == enemy)
        {
            return;
        }
        enemy.SetActive(false);
        activeEnemies.Remove(enemy);
        enemyPool.Enqueue(enemy);
    }

    // 扩展对象池
    private void ExpandPool(int amount)
    {
        for (int i = 0; i < amount; i++)
        {
            GameObject enemy = ABMgr.GetInstance().LoadAssetBundleSync<GameObject>("model", "Enemy");
            enemy.transform.SetParent(transform);
            enemy.SetActive(false);
            enemyPool.Enqueue(enemy);
        }
    }

    // 获取所有活跃敌人
    public List<GameObject> GetActiveEnemies()
    {
        return new List<GameObject>(activeEnemies);
    }
}
